package cn.kuporo.seckill.goods.application.listener;

import cn.hutool.core.util.StrUtil;
import cn.kuporo.seckill.common.constants.MQConstants;
import cn.kuporo.seckill.goods.application.cacahe.SeckillGoodsCacheService;
import cn.kuporo.seckill.goods.application.cacahe.SeckillGoodsListCacheService;
import cn.kuporo.seckill.goods.domain.event.SeckillGoodsEvent;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * @author: kuporo
 * @since: 2025/7/9
 * @description:
 */
@Component
@ConditionalOnProperty(name = "message.mq.type", havingValue = "rocketmq")
@RocketMQMessageListener(consumerGroup = MQConstants.EVENT_GOODS_CONSUMER_GROUP, topic = MQConstants.TOPIC_EVENT_ROCKETMQ_GOODS)
@RequiredArgsConstructor
@Slf4j
public class SeckillGoodsRocketMQEventHandler implements RocketMQListener<String> {

    private final SeckillGoodsCacheService seckillGoodsCacheService;
    private final SeckillGoodsListCacheService seckillGoodsListCacheService;
    @Override
    public void onMessage(String message) {
        log.info("rocketmq|goodsEvent|接收秒杀品事件|{}", message);
        if (StrUtil.isEmpty(message)){
            log.info("rocketmq|goodsEvent|接收秒杀品事件参数错误" );
            return;
        }
        SeckillGoodsEvent seckillGoodsEvent = this.getEventMessage(message);
        seckillGoodsCacheService.tryUpdateSeckillGoodsCacheByLock(seckillGoodsEvent.getId(),false);
        seckillGoodsListCacheService.tryUpdateSeckillGoodsCacheByLock(seckillGoodsEvent.getActivityId(), false);
    }

    private SeckillGoodsEvent getEventMessage(String msg){
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String eventStr = jsonObject.getString(MQConstants.MSG_KEY);
        return JSONObject.parseObject(eventStr, SeckillGoodsEvent.class);
    }
}
